package com.example.myapplication.ui.components

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage

import com.example.myapplication.util.FileUtil
import androidx.compose.ui.platform.LocalContext

/**
 * 添加或编辑物品对话框
 */
@Composable
fun AddItemDialog(
    onDismiss: () -> Unit,
    onConfirm: (name: String, description: String?, quantity: Int, imagePath: String?) -> Unit,
    isEditMode: Boolean = false,
    initialName: String = "",
    initialDescription: String = "",
    initialQuantity: Int = 1,
    initialImagePath: String? = null
) {
    var name by remember { mutableStateOf(initialName) }
    var description by remember { mutableStateOf(initialDescription) }
    var quantityText by remember { mutableStateOf(initialQuantity.toString()) }
    var imagePath by remember { mutableStateOf(initialImagePath) }

    val context = LocalContext.current
    // 简化版照片选择器
    val photoPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let {
            val newPath = FileUtil.copyImageToInternalStorage(context, it)
            if (newPath != null) {
                imagePath = newPath
            }
        }
    }

    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = if (isEditMode) "编辑物品" else "添加物品",
                    style = MaterialTheme.typography.headlineSmall
                )

                // 物品名称
                OutlinedTextField(
                    value = name,
                    onValueChange = { name = it },
                    label = { Text("物品名称") },
                    modifier = Modifier.fillMaxWidth(),
                    keyboardOptions = KeyboardOptions(
                        capitalization = KeyboardCapitalization.Words
                    ),
                    singleLine = true
                )

                // 描述
                OutlinedTextField(
                    value = description,
                    onValueChange = { description = it },
                    label = { Text("描述（可选）") },
                    modifier = Modifier.fillMaxWidth(),
                    maxLines = 3
                )

                // 数量
                OutlinedTextField(
                    value = quantityText,
                    onValueChange = { newValue ->
                        if (newValue.isEmpty() || newValue.all { it.isDigit() }) {
                            quantityText = newValue
                        }
                    },
                    label = { Text("数量") },
                    modifier = Modifier.fillMaxWidth(),
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Number
                    ),
                    singleLine = true
                )

                // New: Image Preview and Button
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    AsyncImage(
                        model = imagePath,
                        contentDescription = "物品图片",
                        modifier = Modifier
                            .size(64.dp)
                            .weight(1f),
                        contentScale = ContentScale.Crop
                    )
                    Spacer(modifier = Modifier.width(16.dp))
                    Button(
                        onClick = {
                            photoPickerLauncher.launch("image/*")
                        },
                        modifier = Modifier.weight(2f)
                    ) {
                        Text("选择照片")
                    }
                }


                // 按钮
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    TextButton(onClick = onDismiss) {
                        Text("取消")
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Button(
                        onClick = {
                            if (name.isNotBlank()) {
                                val quantity = quantityText.toIntOrNull() ?: 1
                                onConfirm(
                                    name.trim(),
                                    description.trim().takeIf { it.isNotEmpty() },
                                    maxOf(quantity, 1),
                                    imagePath // Pass the image path
                                )
                            }
                        },
                        enabled = name.isNotBlank()
                    ) {
                        Text(if (isEditMode) "保存" else "添加")
                    }
                }
            }
        }
    }
}